package BookStore.EBook.ConvertorForAndroid;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class ApkGenerator {
	
	private static String PACKAGE = "src" + File.separator+ "bookStore" + File.separator+ "eBook" + File.separator+ "android";
	private static String[] NEED_REPLACED = {"ReadingActivity.java", "ChapterManager.java", "EBookEntryActivity.java"};
	private static String PATTERN_BOOK_NAME = "KEEPFORBOOKNAME";
	private static String PATTERN_BOOK_GUID = "KEEPFORGUID";
	private static String PACKAGE_TOOL = "package.bat";
	
	public static void generateAllFromRepo(String rawRoot, String apkRoot, String templatePath, String workPath)
	{
		File rawPath = new File(rawRoot);
		if (!rawPath.exists() || !rawPath.isDirectory()) {
			System.out.println("Raw root " + rawPath.getAbsolutePath()+" doesn't exist!");
			return;
		}
		
		File apkPath = new File(apkRoot);
		if (!apkPath.exists()) {
			apkPath.mkdirs();
		}
		
		File[] catagories = rawPath.listFiles();
		
		for (int i = 0; i < catagories.length; i++) {
			if (catagories[i].isDirectory())
			{
				String catagory = catagories[i].getName();
				File[] books = catagories[i].listFiles();
				
				for(int j = 0; j < books.length; j++)
				{
					String bookName = books[j].getName();
					generateApkFromRepo(bookName, books[j].getAbsolutePath(), apkRoot + File.separator + catagory, templatePath, workPath);
				}
			}
		}
	}
	
	public static void generateApkFromRepo(String bookName, String rawPath, String apkPath, String templatePath, String workPath)
	{
		File tPath = new File(templatePath);
		if (!tPath.exists() || !tPath.isDirectory()) {
			System.out.println("Template path " + tPath.getAbsolutePath()+" doesn't exist!");
			return;
		}
		
		File wPath = new File(workPath);
		if (!wPath.exists() || !wPath.isDirectory()) {
			System.out.println("Work path " + wPath.getAbsolutePath()+" doesn't exist!");
			return;
		}
		
		File rPath = new File(rawPath);
		if (!rPath.exists() || !rPath.isDirectory()) {
			System.out.println("Raw book " + rPath.getAbsolutePath()+" doesn't exist!");
			return;
		}
		
		File[] files = rPath.listFiles();
		if(files.length <= 0)
		{
			System.out.println("Raw book " + rPath.getAbsolutePath()+" has nothing!");
			return;
		}
		
		String bookGUID = "";
		
		for (int i = 0; i < files.length; i++) {
			if (files[i].isFile())
			{
				String id = files[i].getName();
				if(id.contains("-"))
				{
					//id.replaceAll("\\-", "");
					String[] ids = id.split("-");
					for(int j = 0; j< ids.length; j++)
					{
						bookGUID = bookGUID+ids[j];
					}
				}
			}
		}
		
		if(bookGUID.isEmpty() || bookGUID.length()!=32)
		{
			System.out.println("Raw book " + rPath.getAbsolutePath()+" has no GUID or wrong GUID!");
			return;
		}
		
		// copy template to work folder
		try {
			FileUtil.recreateDir(workPath);
			
			FileUtil.copyDirectiory(templatePath, workPath);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		//copy raw txt files to android res/raw folder
		try {
			String resRawPath = workPath + File.separator + "res" + File.separator + "raw";
			FileUtil.recreateDir(resRawPath);
			
			FileUtil.copyDirectiory(rawPath + File.separator + "raw" , resRawPath);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		//replace the app_name with book name
		String strPath = workPath + File.separator + "res" + File.separator + "values" + File.separator + "strings.xml";
		replaceStringInFile(strPath, PATTERN_BOOK_NAME , bookName);
		
		//add GUID to the package name and space name 
		String manifestPath = workPath + File.separator + "AndroidManifest.xml";
		replaceStringInFile(manifestPath, PATTERN_BOOK_GUID , bookGUID);
		
		for(int i = 0; i < NEED_REPLACED.length; i++)
		{
			replaceStringInFile(workPath + File.separator + PACKAGE + File.separator + NEED_REPLACED[i], PATTERN_BOOK_GUID , bookGUID);
		}
		
		// run package script
		String command = workPath + File.separator + PACKAGE_TOOL + " " +workPath + " " + bookGUID + " final";
		try {
			Process pr=Runtime.getRuntime().exec(command);
			
			String txt;
	        InputStream ins = pr.getInputStream();

	        InputStreamReader insReader = new InputStreamReader(ins);
	        BufferedReader bufferedReader = new BufferedReader(insReader);

	        while ((txt = bufferedReader.readLine()) != null)
	        {
	        	//System.out.println(txt);
	        }
	        
			pr.waitFor();
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		
		// move the final apk file to apk repo
		try {
			File target = new File(apkPath);
			if (!target.exists()) {
				target.mkdirs();
			}
			
			FileUtil.copyFile(new File(workPath + File.separator + "final.apk"), new File(apkPath + File.separator + bookName + ".apk"));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	
	private static void replaceStringInFile(String filePath, String pattern, String replaceStr)
	{
		try {
			File oldFile = new File(filePath);
			File newFile = FileUtil.replaceAllInFile(oldFile, pattern, replaceStr);
			
			FileUtil.copyFile(newFile, oldFile);
			newFile.delete();
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		
		String bookRepo = "G:\\BookStore\\EbookForAndroid-Raw\\[历史军事]\\不一样的大军阀";
		String apkPath = "G:\\BookStore\\EbookForAndroid-APK\\[历史军事]";
		String templatePath = "G:\\BookStore\\BookStore.EBook.Android.Template";
		String workPath = "G:\\BookStore\\BookStore.EBook.Android";
		
		//ApkGenerator.generateApkFromRepo("不一样的大军阀", bookRepo, apkPath, templatePath, workPath);
		
		String rawRoot = "G:\\BookStore\\EbookForAndroid-Raw";
		String apkRoot = "G:\\BookStore\\EbookForAndroid-APK";
		ApkGenerator.generateAllFromRepo(rawRoot, apkRoot, templatePath, workPath);
		
	}

}
